package ppa.marc.importer.reader;

import java.io.File; 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import ppa.marc.RecordReader;
import ppa.marc.domain.Record;

public class TextualMarcRecordReader implements RecordsReader {
	private final RecordReader recordReader;
	private final PrintStream errorOutput;

	public TextualMarcRecordReader(RecordReader recordReader, PrintStream errorOutput) {
		this.recordReader = recordReader;
		this.errorOutput = errorOutput;
	}

	public List<Record> readRecords(File inputFile) {
		List<Record> records = new ArrayList<Record>();
		FileInputStream inputStream = null;
		try {
			inputStream = openInputStream(inputFile);
			records = recordReader.read(inputStream);
		} catch (FileNotFoundException fileNotFoundException) {
			errorOutput.println("File " + inputFile.getAbsolutePath() + " not found: " + fileNotFoundException.getMessage());
		} catch (IOException ioException) {
			errorOutput.println("Unable to read records from file " + inputFile.getAbsolutePath() + ": " + ioException.getMessage());
		} finally {
			closeStream(inputStream);
		}
		return records;
	}

	private void closeStream(FileInputStream inputStream) {
		try {
			inputStream.close();
		} catch (Exception ignored) {
		}
	}

	FileInputStream openInputStream(File inputFile) throws FileNotFoundException {
		return new FileInputStream(inputFile);
	}
}
